<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="keyword" placeholder="菜单名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

  <!--列表-->
  <el-table :data="menu" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
    <el-table-column type="selection" width="55">
    </el-table-column>
    <el-table-column type="index" width="60">
    </el-table-column>
    <el-table-column prop="name" label="菜单名称" width="130" sortable>
    </el-table-column>
    <el-table-column prop="component" label="组件" width="280" sortable>
    </el-table-column>
    <el-table-column prop="url" label="路径" width="170" sortable>
    </el-table-column>
    <el-table-column prop="parent.name" label="上级菜单" width="170" sortable>
    </el-table-column>
    <el-table-column prop="state" label="菜单状态" width="170" sortable>
      <template scope="scope">
        <span v-if="scope.row.state==true" style="color: green">启用</span>
        <span v-else style="color: red">禁用</span>
      </template>
    </el-table-column>

    <el-table-column label="操作" width="170">
      <template scope="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>



    <!--编辑与新增界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="组件" prop="component">
          <el-input v-model="saveForm.component" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="路径" prop="url">
          <el-input v-model="saveForm.url" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="email">
          <el-input-number v-model="saveForm.index" auto-complete="off"></el-input-number>
        </el-form-item>
        <el-form-item label="上级菜单">
          <!-- <el-input v-model="saveForm.parent_id"></el-input>-->
          <el-cascader v-model="saveForm.parentId"
                       :options="menuTree"
                       :props="{ checkStrictly: true,label:'name',value:'id' }"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="菜单状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="true">启用</el-radio>
            <el-radio class="radio" :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
	export default {
	  //定义模型数据
		data() {
			return {
        //关键词
        keyword: '',
        //标题
        title:'',
        saveFormVisible: false,//添加和修改对话框是否显示
        saveLoading: false,  //保存的忙等框 - 在提交按钮上
        sels: [],//列表选中列
        menu: [],//列表数据
        menuTree:[],//
        listLoading: false,//加载框
        totals: 0,
        currentPage: 1,
        pageSize: 5,

        editFormVisible: false,//编辑界面是否显示
        editLoading: false,
        saveFormRules: {
          username: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ]
        },
        //编辑界面数据
        saveForm: {
          id: null,
          name: '',
          component: '',
          url: '',
          index:1,
          state:true,
          parentId: null,
        },
			}
		},
    methods:{
		  //1.列表
      getMenu() {
        let para = {
          "currentPage": this.currentPage,
          "pageSize": this.pageSize,
          "keyword": this.keyword
        };
        this.listLoading = true;
        this.$http.post("/menu",para).then(res=>{
          //关闭盲等
          this.listLoading = false;
          //显示分页数据
          this.menu=res.data.data;
          //计算分页栏
          this.totals = res.data.totals;
        })
      },
      //2.点击当前页的逻辑
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getMenu();
      },
      //3.高級查詢
      keywordQuery(){
        this.currentPage=1;
        this.getMenu();
      },
      //4.刪除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', { //确认框
          type: 'warning'
        }).then(() => {//点击确定的时候
          //開啟忙等框
          this.listLoading = true;
           //发起请求
          this.$http.delete("/menu/"+row.id).then(res=>{
            //关闭忙等框
            this.listLoading = false;
            if(res.data.success){ //成功
              this.$message.success("删除成功");
              //对当前页的处理
              let totalPage = Math.ceil(this.totals/this.pageSize);//算出总页数
              //如果当前页是最后一页                        并且是最后一条数据             并且不是第一页
              if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
                this.currentPage = this.currentPage-1;
              }
              this.getMenu();
            }else{
              this.$message.error("网络繁忙，请稍后重试!!!【500】")
            }
          }).catch(res=>{
            this.$message.error("网络繁忙，请稍后重试!!!【400,404】")
          })
        }).catch(() => { //点击取消的时候
        });
      },
      //5.选项改变时触发
      selsChange: function (sels) {
        console.log(sels);
        this.sels = sels;
      },
      //6.批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);//[1,2,3]
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/menu",ids).then(res=>{
            //关闭忙等框
            this.listLoading = false;
            if(res.data.success){
              //弹出成功信息
              this.$message.success("删除成功");
              this.currentPage = 1;
              //重新获取新的数据
              this.getMenu();
            }else{
              this.$message.error("网络繁忙，请稍后重试!!!【500】")
            }
          }).catch(res => {
            this.$message.error("网络繁忙，请稍后重试!!!【400,404】")
          })
        }).catch(() => {
        });
      },
      //7.点击添加按钮显示对话框
      handleAdd: function () {
        this.saveForm = {
          name: '',
          component: '',
          url: '',
          index:1,
          state:true,
          parentId: null,
        };
        this.title = "添加";
        //显示对话框
        this.saveFormVisible = true;
        //上级菜单无限树级
        this.getmenuTree();
      },
      //8.点击修改按钮显示对话框
      handleEdit: function (index, row) {
        //回显数据：避免以前的数据发生改变
        this.saveForm = Object.assign({}, row);
        this.title = "修改";
        //显示对话框
        this.saveFormVisible = true;
        //上级菜单无限树级
        this.getmenuTree();
      },
      //9.提交添加或修改的数据
      saveSubmit: function () {
        //所有的对话框中 的 名称为saveForm的对话框  验证上面的表单项验证通过就返回true
        this.$refs.saveForm.validate((valid) => { //表单验证
          if (valid) {//表单验证通过
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              let para = Object.assign({}, this.saveForm);

              //对上级菜单做数据处理：选了上级菜单之后，有可能数据是这样的结构 [],[3,8],[8],[2,3,8]
              let arr = para.parentId;
              console.log(arr);
              if(arr && arr.length==0){
                para.parentId = null;
              }
              if(arr && arr.length>0){ //[1,13]
                para.parentId = arr[arr.length-1];
              }

              this.$http.put("/menu",para).then(res=>{
                //关闭忙等框
                this.saveLoading = false;
                //关闭对话框
                this.saveFormVisible = false;
                if(res.data.success){
                  //弹出成功信息
                  this.$message.success("操作成功");
                  //重新获取新的数据
                  this.getMenu();
                }else{
                  this.$message.error("网络繁忙，请稍后重试!!!【500】")
                }
              }).catch(res=>{
                this.$message.error("网络繁忙，请稍后重试!!!【400,404】")
              })
            });
          }
        });
      },
      //无限树级
      getmenuTree(){
        this.$http.get("/menu/menuTree").then(res=>{
          this.menuTree=res.data;
        })
      }
    },
    mounted() {
      this.getMenu();
    }
	}

</script>

<style scoped>

</style>